from pathlib import Path
import json
from datetime import datetime
from typing import List, Dict, Any
import glob

class ModelCallService:
    def __init__(self):
        self.logs_dir = Path("logs/model_calls")

    def get_model_calls(self, start_date: str = None, end_date: str = None) -> List[Dict[Any, Any]]:
        """
        Retrieve model call records with optional date filtering
        """
        if not self.logs_dir.exists():
            return []
            
        records = []
        all_files = glob.glob(str(self.logs_dir / "model_calls_*.jsonl"))
        
        for file_path in sorted(all_files):
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    try:
                        record = json.loads(line)
                        
                        if self._should_include_record(record, start_date, end_date):
                            # Add computed fields
                            record["success"] = record.get("error") is None
                            record["duration_ms"] = round(record.get("duration", 0) * 1000, 2)
                            
                            # Format input content
                            if "input" in record:
                                record["formatted_input"] = json.dumps(record["input"], indent=2, ensure_ascii=False)
                            
                            # Format output content
                            if "output" in record:
                                record["formatted_output"] = json.dumps(record["output"], indent=2, ensure_ascii=False)
                            elif "error" in record:
                                record["formatted_output"] = record["error"]
                            
                            records.append(record)
                    except json.JSONDecodeError:
                        continue
                        
        return records[-100:]  # Return last 100 records
        
    def _should_include_record(self, record: Dict, start_date: str, end_date: str) -> bool:
        """Helper method to determine if a record should be included based on dates"""
        if not (start_date or end_date):
            return True
            
        try:
            record_date = datetime.fromisoformat(record["timestamp"].split(".")[0])
            
            if start_date and record_date < datetime.fromisoformat(start_date):
                return False
            if end_date and record_date > datetime.fromisoformat(end_date):
                return False
                
            return True
        except (KeyError, ValueError):
            return False
